package com.runrunfast.fxj.controller;

import com.runrunfast.fxj.utils.ShiroKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author: 陈胤训
 * @create: 2019-03-13 16:19
 **/

@Api(value = "后台管理",tags={"登录注销"})
@RestController
@RequestMapping("/admin")
public class AdminController {

    public static final Logger LOG = LoggerFactory.getLogger(AdminController.class);

    @GetMapping("/login")
    @ResponseBody
    public  String login(){
        return "login";
    }

    @GetMapping("/unauth")
    @ResponseBody
    public  String index(){
        return "没有授权";
    }

    /**
     * 登录
     *
     * @param phone
     * @param password
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/signin")
    public String submitLogin(@RequestParam("phone") String phone, @RequestParam("password") String password,
                              @RequestParam(value = "rememberMe",required = false) boolean rememberMe,
                              @RequestParam(value = "kaptcha",required = false)String kaptcha) {
        UsernamePasswordToken token = new UsernamePasswordToken(phone, password, true);
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        try {
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            currentUser.login(token);

            return "成功";
        } catch (IncorrectCredentialsException e) {
            LOG.error("登录失败，手机号码[{}]", phone, e.getMessage());
            token.clear();
            return  "用户名或者密码错误";
        } catch (Exception e) {
            LOG.error("登录失败，手机号码[{}]", phone, e);
            token.clear();
            return "系统错误";
        }
    }

    /**
     * 使用权限管理工具进行用户的退出，跳出登录，给出提示信息
     *
     * @param redirectAttributes
     * @return
     */
    @ApiOperation(value = "注销")
    @GetMapping("/logout1")
    public String logout(RedirectAttributes redirectAttributes) {

            ShiroKit.getSubject().logout();


        return "注销成功";
    }
}
